#include "stdafx.h"
#include "HookApi.h"
#include "HookWinSock.h"
#include "FilterFuns.h"
#include <ws2spi.h>

#pragma comment(lib,"ws2_32.lib")

bool m_Enabled=FALSE;
Parameter m_Parameter={0};
WSPPROC_TABLE nextproctable;

typedef int (WSPAPI *TrueWSPStartup)(
 __in          WORD wVersionRequested,
  __out         LPWSPDATA lpWSPData,
  __in          LPWSAPROTOCOL_INFO lpProtocolInfo,
  __in          WSPUPCALLTABLE UpcallTable,
  __out         LPWSPPROC_TABLE lpProcTable

);

TrueWSPStartup pfnTrueWSPStartup;

int WSPAPI MyWSPCONNECT(
    SOCKET s,
    const struct sockaddr FAR * name,
    int namelen,
    LPWSABUF lpCallerData,
    LPWSABUF lpCalleeData,
    LPQOS lpSQOS,
    LPQOS lpGQOS,
    LPINT lpErrno
	)
{
	/*char *add=inet_ntoa(((sockaddr_in *)name)->sin_addr);
	MessageBox(NULL,add,"DNS",0);
	((sockaddr_in *)name)->sin_addr.s_addr=inet_addr("127.0.0.1");
	((sockaddr_in *)name)->sin_port=htons(80);*/
	int ret= nextproctable.lpWSPConnect(s,name,namelen,lpCallerData,lpCalleeData,lpSQOS,lpGQOS,lpErrno);
	return ret;
}

int WSPAPI MyWSPRecv(
  __in          SOCKET s,
  __out      LPWSABUF lpBuffers,
  __in          DWORD dwBufferCount,
  __out         LPDWORD lpNumberOfBytesRecvd,
  __out      LPDWORD lpFlags,
  __in          LPWSAOVERLAPPED lpOverlapped,
  __in          LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
  __in          LPWSATHREADID lpThreadId,
  __out         LPINT lpErrno
  )
{

	int ret= nextproctable.lpWSPRecv(s,lpBuffers,dwBufferCount,lpNumberOfBytesRecvd,lpFlags,lpOverlapped,lpCompletionRoutine,lpThreadId,lpErrno);

	if(m_Enabled)
	{
		for(int i=0;i<m_Parameter.gameCount;i++)
		{
			FilterGame(lpBuffers->buf,lpNumberOfBytesRecvd,&m_Parameter.filter[0]);
		}
	}

	return ret;
}


 int WSPAPI MyWSPStartup(
  DWORD RetAddr,
  TrueWSPStartup pfnTrueWSPStartup,
  __in          WORD wVersionRequested,
  __out         LPWSPDATA lpWSPData,
  __in          LPWSAPROTOCOL_INFO lpProtocolInfo,
  __in          WSPUPCALLTABLE UpcallTable,
  __out         LPWSPPROC_TABLE lpProcTable

)
 {
    MessageBeep(MB_ICONINFORMATION);
	int ret= pfnTrueWSPStartup(wVersionRequested,lpWSPData,lpProtocolInfo,UpcallTable,lpProcTable);
	nextproctable=*lpProcTable;
	lpProcTable->lpWSPRecv=MyWSPRecv;
	//lpProcTable->lpWSPConnect=MyWSPCONNECT;
	return ret;
 }

 void HookWinSock()
 {
	  InstallHookApi("mswsock.dll", "WSPStartup", MyWSPStartup);
 }

void  SetMode(bool enabled)
{
	m_Enabled=enabled;
}

bool  GetMode()
{
	return m_Enabled;
}

PParameter GetParameter()
{
	return &m_Parameter;
}

